package com.ygswglxt.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private static final String SECRET = "ygswglxtSecretKeyForJwtTokenGeneration2024MustBeAtLeast32Bytes";
    private static final Key KEY = Keys.hmacShaKeyFor(SECRET.getBytes());
    private static final long EXPIRATION = 86400000L; // 24小时

    public static String generateToken(Long userId, String username, String role) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        claims.put("role", role);
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    public static Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    public static UserInfo getUserInfo(String token) {
        Claims claims = parseToken(token);
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Long.valueOf(claims.get("userId").toString()));
        userInfo.setUsername(claims.get("username").toString());
        userInfo.setRole(claims.get("role").toString());
        return userInfo;
    }
}

